package com.ly.heart.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.ly.common.PageParam;
import com.ly.common.core.domain.AjaxResult;
import com.ly.common.core.domain.entity.SysDept;
import com.ly.common.exception.CustomException;
import com.ly.common.utils.DateUtils;
import com.ly.common.utils.SecurityUtils;
import com.ly.common.utils.StringUtils;
import com.ly.common.utils.erp.CommonUtil;
import com.ly.common.utils.erp.ConstUtil;
import com.ly.common.utils.erp.KingConstUtil;
import com.ly.common.utils.erp.SnowflakeIdWorker;
import com.ly.heart.domain.*;
import com.ly.heart.domain.dto.KingFinancePayDto;
import com.ly.heart.domain.dto.KingFinancePayRefundDto;
import com.ly.heart.domain.dto.KingInvoicePayableOtherDto;
import com.ly.heart.domain.dto.StartProcessDto;
import com.ly.common.core.domain.ActCurrentTaskVo;
import com.ly.heart.domain.vo.KingFinancePayBillVo;
import com.ly.heart.mapper.KingFinancePayBillMapper;
import com.ly.heart.service.*;
import com.ly.heart.util.CurrentUserUtil;
import com.ly.system.service.ISysDeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 金蝶-财务-应付票据Service业务层处理
 *
 * @author wutao
 * @date 2024-06-19
 */
@Service
@Slf4j
public class KingFinancePayBillServiceImpl extends ServiceImpl<KingFinancePayBillMapper, KingFinancePayBillEntity> implements IKingFinancePayBillService {

    @Resource
    private KingFinancePayBillMapper kingFinancePayBillEntityMapper;
    @Resource
    private IKingFinancePaySettlementBillService iKingFinancePaySettlementBillService;
    @Resource
    private IActModelService iActModelService;
    @Resource
    private ICustomerService iCustomerService;
    @Resource
    private ISupplierService iSupplierService;
    @Resource
    private IKingBaseTransactionsCompanyService iKingBaseTransactionsCompanyService;
    @Resource
    private ISysDeptService iSysDeptService;
    @Resource
    private IActTaskCommentService iActTaskCommentService;
    @Resource
    private IKingFinancePayService iKingFinancePayService;
    @Resource
    private IKingBankAccountService iKingBankAccountService;
    @Resource
    private IKingFinancePayRefundService iKingFinancePayRefundService;
    @Resource
    private IKingInvoicePayableOtherService iKingInvoicePayableOtherService;

    /**
     * 查询金蝶-财务-应付票据
     *
     * @param id 金蝶-财务-应付票据ID
     * @return 金蝶-财务-应付票据
     */
    @Override
    public KingFinancePayBillVo selectKingFinancePayBillEntityById(String id) {
        KingFinancePayBillEntity payBillEntity = kingFinancePayBillEntityMapper.selectKingFinancePayBillEntityById(id);
        String transactionCompanyName = getCompanyName(payBillEntity.getReceiptDeptType(), payBillEntity.getReceiptDeptId());
        payBillEntity.setReceiptDeptName(transactionCompanyName);
        //KingFinancePayEntity payEntity = kingFinancePayMapper.selectOne(new QueryWrapper<KingFinancePayEntity>().eq("pay_bill_id", id));
        KingFinancePayBillVo kingFinancePayBillVo = new KingFinancePayBillVo();
        kingFinancePayBillVo/*.setKingFinancePayEntity(payEntity)*/.setKingFinancePayBillEntity(payBillEntity);
        return kingFinancePayBillVo;
    }

    /**
     * 查询金蝶-财务-应付票据列表
     *
     * @param kingFinancePayBillEntity 金蝶-财务-应付票据
     * @return 金蝶-财务-应付票据
     */
    @Override
    public AjaxResult selectKingFinancePayBillEntityList(KingFinancePayBillEntity kingFinancePayBillEntity) {
        kingFinancePayBillEntity.setPage((kingFinancePayBillEntity.getPage() - 1) * kingFinancePayBillEntity.getLimit());
        List<KingFinancePayBillEntity> kingFinancePayBillEntities = kingFinancePayBillEntityMapper.selectKingFinancePayBillEntityList(kingFinancePayBillEntity);
        kingFinancePayBillEntities.forEach(payBill -> {
            String transactionCompanyName = getCompanyName(payBill.getReceiptDeptType(), payBill.getReceiptDeptId());
            payBill.setReceiptDeptName(transactionCompanyName);
            //处理最后一个审批人
            ActTaskCommentEntity actTaskCommentEntity = iActTaskCommentService.queryLastComment(payBill.getInstanceId());
            if (actTaskCommentEntity != null) {
                payBill.setApprovedUser(actTaskCommentEntity.getApprovedUser());
                payBill.setApprovedRemark(actTaskCommentEntity.getRemark());
            }
            //任务信息
            ActCurrentTaskVo currentTaskVo = iActModelService.getCurrentTaskByInstanceId(payBill.getInstanceId());
            Optional.ofNullable(currentTaskVo).ifPresent(currentTask -> {
                payBill.setCurrentTask(currentTask);
            });
        });
        Integer integer = kingFinancePayBillEntityMapper.queryCount(kingFinancePayBillEntity);
        PageParam p = new PageParam();
        p.setRecords(kingFinancePayBillEntities).setTotal(integer);
        return AjaxResult.success(p);
    }

    /**
     * 新增金蝶-财务-应付票据
     *
     * @param kingFinancePayBillEntity 金蝶-财务-应付票据
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public AjaxResult draft(KingFinancePayBillEntity kingFinancePayBillEntity) {
        //到期日必须大于签发日
        boolean after = CommonUtil.isAfter(kingFinancePayBillEntity.getIssuanceTime(), kingFinancePayBillEntity.getDueTime());
        if (!after) {
            return AjaxResult.error("到期日必须大于签发日");
        }
        kingFinancePayBillEntity.setId(SnowflakeIdWorker.getInstance().nextStringId());
        int count = this.count();
        kingFinancePayBillEntity.setBillSerialNo("YFPJ".concat(String.format("%08d", count)));
        kingFinancePayBillEntity.setDeptId(CurrentUserUtil.getCompanyId());
        kingFinancePayBillEntity.setPayDeptId(CurrentUserUtil.getCompanyId());
        kingFinancePayBillEntity.setSettlementDeptId(CurrentUserUtil.getCompanyId());
        kingFinancePayBillEntity.setSettlementStatus(KingConstUtil.FINANCE_PAY_BILL_SETTLEMENT_STATUS_EMPTY);
        kingFinancePayBillEntity.setState(ConstUtil.STATE_IN_DRAFT);
        kingFinancePayBillEntity.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId());
        kingFinancePayBillEntity.setCreateTime(DateUtils.getNowDate());
        boolean save = this.save(kingFinancePayBillEntity);
        if (!save) {
            throw new CustomException("暂存应付票据失败！");
        }
        return AjaxResult.success("暂存应付票据成功", kingFinancePayBillEntity.getId());
    }

    public AjaxResult submit(KingFinancePayBillEntity kingFinancePayBillEntity) {
        if (StringUtils.isBlank(kingFinancePayBillEntity.getId())) {
            return AjaxResult.error("清先暂存该单据！");
        }
        //创建审批流
        StartProcessDto startDto = new StartProcessDto().
                setBusinessId(kingFinancePayBillEntity.getId()).
                setBusinessType(kingFinancePayBillEntity.getBusinessType()).setModelId(kingFinancePayBillEntity.getModelId()).
                setBusinessName("采购合同_".concat(kingFinancePayBillEntity.getId()));
        String instanceId = iActModelService.startProcess(startDto);
        kingFinancePayBillEntity.setInstanceId(instanceId);
        boolean update = this.update(new LambdaUpdateWrapper<KingFinancePayBillEntity>().
                set(KingFinancePayBillEntity::getState, ConstUtil.STATE_IN_PROCESS).
                set(KingFinancePayBillEntity::getInstanceId, instanceId).
                eq(KingFinancePayBillEntity::getId, kingFinancePayBillEntity.getId()));
        if (!update) {
            throw new CustomException("提交应付票据失败！");
        }
        return AjaxResult.success("提交应付票据成功");
    }


    /**
     * 应付票据审批
     * 1、修改状态
     * 2、生成付款单【结算方式：银行承兑汇票】，付款单需要加上源单类型，源单单号,此时我方银行账户为空（选择结算方式为承兑方式时为空，不影响账户余额）
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public AjaxResult approve(String id) {
        boolean update = this.update(new LambdaUpdateWrapper<KingFinancePayBillEntity>().set(KingFinancePayBillEntity::getState, ConstUtil.STATE_FINISH).eq(KingFinancePayBillEntity::getId, id));
        if (!update) {
            throw new CustomException("修改审批状态失败！");
        }
        KingFinancePayBillEntity payBillEntity = kingFinancePayBillEntityMapper.selectKingFinancePayBillEntityById(id);
        KingFinancePayDto dto = new KingFinancePayDto();
        KingFinancePayEntity payEntity = new KingFinancePayEntity();
        payEntity.setDocTypeCode(KingConstUtil.PAY_PURCHASE_PAY);
        payEntity.setTransactionCompanyType(payBillEntity.getReceiptDeptType());
        payEntity.setTransactionCompanyId(payBillEntity.getReceiptDeptId());
        payEntity.setReceiptDeptType(payBillEntity.getReceiptDeptType());
        payEntity.setReceiptDeptId(payBillEntity.getReceiptDeptId());
        payEntity.setBusinessTime(DateUtils.getNowDate());
        payEntity.setKingBaseCurrencyCode(payBillEntity.getKingBaseCurrencyCode());
        payEntity.setSettlementDeptId(payBillEntity.getSettlementDeptId());
        payEntity.setPayDeptId(payBillEntity.getPayDeptId());
        payEntity.setProcureCompanyId(payBillEntity.getPurchasingOrgId());
        payEntity.setCopeMoney(payBillEntity.getFaceAmount());//应付金额
        payEntity.setActualMoney(payBillEntity.getFaceAmount());//实付金额
        payEntity.setCreateBy(payBillEntity.getCreateBy());
        payEntity.setSourceDocType(KingConstUtil.PAY_TYPE_PAY_BILL);
        dto.setKingFinancePayEntity(payEntity);
        //组装明细
        List<KingFinancePayDetailEntity> payDetailEntities = new ArrayList<>();
        KingFinancePayDetailEntity financePayDetailEntity = new KingFinancePayDetailEntity();
        financePayDetailEntity.setKingSettlementTypeCode(KingConstUtil.SETT_TYPE_YHCDHP);
        financePayDetailEntity.setPayReceiptPurposeCode(KingConstUtil.PURPOSE_YFK);
        financePayDetailEntity.setPrepaidItemType("2"); //预付项目类型为采购订单
        financePayDetailEntity.setCopeMoney(payBillEntity.getFaceAmount());
        financePayDetailEntity.setActualMoney(payBillEntity.getFaceAmount());
        financePayDetailEntity.setDiscountedMoney(payBillEntity.getFaceAmount());
        financePayDetailEntity.setLineNumber("1");
        financePayDetailEntity.setCreateBy(payBillEntity.getCreateBy());
        payDetailEntities.add(financePayDetailEntity);
        dto.setKingFinancePayDetailEntities(payDetailEntities);
        iKingFinancePayService.draft(dto);
        return AjaxResult.success();
    }

    /**
     * 修改金蝶-财务-应付票据
     *
     * @param kingFinancePayBillEntity 金蝶-财务-应付票据
     * @return 结果
     */
    @Override
    public AjaxResult updateKingFinancePayBillEntity(KingFinancePayBillEntity kingFinancePayBillEntity) {
        kingFinancePayBillEntity.setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserId());
        kingFinancePayBillEntity.setUpdateTime(DateUtils.getNowDate());
        boolean b = this.updateById(kingFinancePayBillEntity);
        if (!b) {
            throw new CustomException("修改应付票据失败！");
        }
        return AjaxResult.success();
    }

    /**
     * 财务-应付票据-到期支付操作
     * 1、检查应付票据的数据状态是否为已审核
     * 2、新增应付票据结算单
     * 3、修改应付票据结算状态为到期付款
     *
     * @param kingFinancePaySettlementBillEntity
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public AjaxResult pay(KingFinancePaySettlementBillEntity kingFinancePaySettlementBillEntity) {
        //1.判断数据状态
        KingFinancePayBillEntity payBill = baseMapper.selectById(kingFinancePaySettlementBillEntity.getPayBillId());
        if (!ConstUtil.STATE_FINISH.equals(payBill.getState())) {
            return AjaxResult.error("选中的单据还未审核通过，不能进行操作！");
        }
        if (!KingConstUtil.FINANCE_PAY_BILL_SETTLEMENT_STATUS_EMPTY.equals(payBill.getSettlementStatus())) {
            return AjaxResult.error("单据已经到期付款或者退票，不能执行操作！");
        }
        //填充部分应付票据的数据
        kingFinancePaySettlementBillEntity.setDocTypeCode(KingConstUtil.KING_PAY_BILL_PAYMENT);
        kingFinancePaySettlementBillEntity.setBizTime(DateUtils.getNowDate());
        kingFinancePaySettlementBillEntity.setSettlementDeptId(payBill.getSettlementDeptId());
        kingFinancePaySettlementBillEntity.setPayDeptId(payBill.getPayDeptId());
        kingFinancePaySettlementBillEntity.setTransactionCompanyType(payBill.getReceiptDeptType());
        kingFinancePaySettlementBillEntity.setTransactionCompanyId(payBill.getReceiptDeptId());
        kingFinancePaySettlementBillEntity.setBaseCurrencyId(payBill.getKingBaseCurrencyId());
        kingFinancePaySettlementBillEntity.setBillSerialNo(payBill.getBillSerialNo());
        kingFinancePaySettlementBillEntity.setBillNo(payBill.getBillNo());
        kingFinancePaySettlementBillEntity.setId(SnowflakeIdWorker.getInstance().nextStringId());
        kingFinancePaySettlementBillEntity.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId());
        kingFinancePaySettlementBillEntity.setCreateTime(DateUtils.getNowDate());
        //2.新增应付票据结算单
        boolean save = iKingFinancePaySettlementBillService.save(kingFinancePaySettlementBillEntity);
        if (!save) {
            log.error("应付票据Id->{}，新增应付票据结算单失败.", kingFinancePaySettlementBillEntity.getPayBillId());
            throw new RuntimeException("下推应付票据结算单失败！");
        }
        //3.修改应付票据结算状态为到期付款
        boolean update = this.update(new UpdateWrapper<KingFinancePayBillEntity>().set("settlement_status", KingConstUtil.FINANCE_PAY_BILL_SETTLEMENT_STATUS_PAY).eq("id", kingFinancePaySettlementBillEntity.getPayBillId()));
        if (!update) {
            log.error("应付票据Id->{}，修改结算状态失败.", kingFinancePaySettlementBillEntity.getPayBillId());
            throw new RuntimeException("下推应付票据结算单失败！");
        }
        //4.扣减付款账户期初余额，扣减额数是实付金额
        KingBankAccountEntity one = iKingBankAccountService.getOne(new LambdaQueryWrapper<KingBankAccountEntity>().
                eq(KingBankAccountEntity::getId, payBill.getPayBankId()));
        if (one != null) {
            double balance = Double.parseDouble(StringUtils.isBlank(one.getOpeningBalance()) ? "0" : one.getOpeningBalance());
            double actual = Double.parseDouble(StringUtils.isBlank(kingFinancePaySettlementBillEntity.getActualMoney()) ? "0" : kingFinancePaySettlementBillEntity.getActualMoney());
            if (balance < actual) {
                throw new CustomException("【" + payBill.getPayBankAccount() + "】的账户余额不够，不能到期支付！");
            }
            String s = CommonUtil.subStr(one.getOpeningBalance(), kingFinancePaySettlementBillEntity.getActualMoney(), 2);
            boolean updateBalance = iKingBankAccountService.update(new LambdaUpdateWrapper<KingBankAccountEntity>().
                    set(KingBankAccountEntity::getOpeningBalance, s).
                    eq(KingBankAccountEntity::getId, payBill.getPayBankId()));
            if (!updateBalance) {
                throw new CustomException("修改期初余额失败！");
            }
        }
        return AjaxResult.success("到期付款成功");
    }

    /**
     * 应付票据退款操作
     * 1、应付票据结算单【单据类型：应付票据退票】
     * 2、生成其他应付单或者付款退款单【采购业务退款单】
     *
     * @param kingFinancePaySettlementBillEntity
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public AjaxResult refund(KingFinancePaySettlementBillEntity kingFinancePaySettlementBillEntity) {
        //1.判断数据状态
        KingFinancePayBillEntity payBill = kingFinancePayBillEntityMapper.selectKingFinancePayBillEntityById(kingFinancePaySettlementBillEntity.getPayBillId());/* baseMapper.selectById(kingFinancePaySettlementBillEntity.getPayBillId());*/
        if (!ConstUtil.STATE_FINISH.equals(payBill.getState())) {
            return AjaxResult.error("选中的单据还未审核通过，不能进行操作！");
        }
        if (!KingConstUtil.FINANCE_PAY_BILL_SETTLEMENT_STATUS_EMPTY.equals(payBill.getSettlementStatus())) {
            return AjaxResult.error("单据已经到期付款或者退票，不能执行操作！");
        }
        //1.生成应付票据结算单
        kingFinancePaySettlementBillEntity.setDocTypeCode(KingConstUtil.KING_PAY_BILL_REFUND);
        kingFinancePaySettlementBillEntity.setSettlementDeptId(payBill.getSettlementDeptId());
        kingFinancePaySettlementBillEntity.setPayDeptId(payBill.getPayDeptId());
        kingFinancePaySettlementBillEntity.setTransactionCompanyType(payBill.getReceiptDeptType());
        kingFinancePaySettlementBillEntity.setTransactionCompanyId(payBill.getReceiptDeptId());
        kingFinancePaySettlementBillEntity.setBaseCurrencyId(payBill.getKingBaseCurrencyId());
        kingFinancePaySettlementBillEntity.setBillSerialNo(payBill.getBillSerialNo());
        kingFinancePaySettlementBillEntity.setBillNo(payBill.getBillNo());
        kingFinancePaySettlementBillEntity.setId(SnowflakeIdWorker.getInstance().nextStringId());
        kingFinancePaySettlementBillEntity.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId());
        kingFinancePaySettlementBillEntity.setCreateTime(DateUtils.getNowDate());
        boolean save = iKingFinancePaySettlementBillService.save(kingFinancePaySettlementBillEntity);
        if (!save) {
            log.error("应付票据Id->{}，新增应付票据结算单失败.", kingFinancePaySettlementBillEntity.getPayBillId());
            throw new RuntimeException("下推应付票据结算单失败！");
        }
        log.info("应付票据退票，生成应付票据结算单成功。");
        if (kingFinancePaySettlementBillEntity.getBillTypeCode().equals(KingConstUtil.KING_PAY_REFUND)) {
            //2.处理付款退款单
            KingFinancePayRefundDto dto = new KingFinancePayRefundDto();
            KingFinancePayRefundEntity payRefundEntity = new KingFinancePayRefundEntity();
            payRefundEntity.setId(SnowflakeIdWorker.getInstance().nextStringId());
            payRefundEntity.setDocTypeCode(KingConstUtil.PAY_REFUND_PUR_REFUND);
            payRefundEntity.setBusinessTime(kingFinancePaySettlementBillEntity.getBizTime());
            payRefundEntity.setTransactionCompanyType(kingFinancePaySettlementBillEntity.getTransactionCompanyType());
            payRefundEntity.setTransactionCompanyId(kingFinancePaySettlementBillEntity.getTransactionCompanyId());
            payRefundEntity.setPayDeptType(kingFinancePaySettlementBillEntity.getTransactionCompanyType());
            payRefundEntity.setPayDeptId(kingFinancePaySettlementBillEntity.getTransactionCompanyId());
            payRefundEntity.setCurrencyCode(payBill.getKingBaseCurrencyCode());
            payRefundEntity.setCopeRefundMoney(kingFinancePaySettlementBillEntity.getRefundAmount());
            payRefundEntity.setActualRefundMoney(kingFinancePaySettlementBillEntity.getRefundAmount());
            payRefundEntity.setPayCompanyId(payBill.getPayDeptId());
            payRefundEntity.setSettlementCompanyId(payBill.getSettlementDeptId());
            payRefundEntity.setProcureCompanyId(payBill.getPurchasingOrgId());
            payRefundEntity.setSourceDocType(KingConstUtil.PAY_REFUND_TYPE_PAY_BILL_REFUND);
            //2.付款退款单明细
            List<KingFinancePayRefundDetailEntity> financePayRefundDetailEntities = new ArrayList<>();
            KingFinancePayRefundDetailEntity payRefundDetailEntity = new KingFinancePayRefundDetailEntity();
            payRefundDetailEntity.setKingSettlementTypeCode(KingConstUtil.SETT_TYPE_PJTP);
            payRefundDetailEntity.setPayPurposeCode(KingConstUtil.PURPOSE_PUR_PAY);
            payRefundDetailEntity.setCopeRefundMoney(kingFinancePaySettlementBillEntity.getRefundAmount());
            payRefundDetailEntity.setActualRefundMoney(kingFinancePaySettlementBillEntity.getRefundAmount());
            payRefundDetailEntity.setRemarks("应付票据退票");
            payRefundDetailEntity.setSourceDocType(KingConstUtil.PAY_REFUND_TYPE_PAY_BILL_REFUND);
            payRefundDetailEntity.setSourceId(payBill.getId());//应付票据Id
            financePayRefundDetailEntities.add(payRefundDetailEntity);
            dto.setKingFinancePayRefundEntity(payRefundEntity);
            dto.setKingFinancePayRefundDetailEntities(financePayRefundDetailEntities);
            iKingFinancePayRefundService.draft(dto);
            log.info("应付票据下推付款退款单成功。");
        } else if (kingFinancePaySettlementBillEntity.getBillTypeCode().equals(KingConstUtil.KING_OTHER_PAYABLE)) {
            //3.处理为其他应付单
            KingInvoicePayableOtherDto dto = new KingInvoicePayableOtherDto();
            KingInvoicePayableOtherEntity payableOtherEntity = new KingInvoicePayableOtherEntity();
            payableOtherEntity.setDocTypeCode(KingConstUtil.KING_OTHER_PAYABLE);
            payableOtherEntity.setBizTime(kingFinancePaySettlementBillEntity.getBizTime());
            payableOtherEntity.setTransactionCompanyType("BD_Supplier");
            payableOtherEntity.setTransactionCompanyId(payBill.getReceiptDeptId());
            payableOtherEntity.setKingBaseCurrencyCode(payBill.getKingBaseCurrencyCode());
            payableOtherEntity.setTotalAmount(payBill.getFaceAmount());
            payableOtherEntity.setDueTime(kingFinancePaySettlementBillEntity.getBizTime());
            payableOtherEntity.setSettlementDeptId(payBill.getSettlementDeptId());
            payableOtherEntity.setPayDeptId(payBill.getPayDeptId());
            payableOtherEntity.setProcureCompanyId(payBill.getPurchasingOrgId());
            payableOtherEntity.setSourceType(2);
            List<KingInvoicePayableReceivableOtherDetailEntity> payableReceivableOtherDetailEntities = new ArrayList<>();
            KingInvoicePayableReceivableOtherDetailEntity payableReceivableOtherDetailEntity = new KingInvoicePayableReceivableOtherDetailEntity();
            payableReceivableOtherDetailEntity.setInvoiceType("0");
            payableReceivableOtherDetailEntity.setTotalAmount(payBill.getFaceAmount());
            payableReceivableOtherDetailEntity.setNoLoanAmount(payBill.getFaceAmount());
            payableReceivableOtherDetailEntity.setRemarks("应付票据退票转其他应付款");
            payableReceivableOtherDetailEntity.setSourceDocType(2);
            payableReceivableOtherDetailEntity.setSourceDocNo(payBill.getId());
            payableReceivableOtherDetailEntities.add(payableReceivableOtherDetailEntity);
            dto.setKingInvoicePayableOtherEntity(payableOtherEntity);
            dto.setKingInvoicePayableReceivableOtherDetailEntities(payableReceivableOtherDetailEntities);
            iKingInvoicePayableOtherService.draft(dto);
        }
        //4.修改应付票据结算状态为退票
        boolean update = this.update(new LambdaUpdateWrapper<KingFinancePayBillEntity>().
                set(KingFinancePayBillEntity::getSettlementStatus, KingConstUtil.FINANCE_PAY_BILL_SETTLEMENT_STATUS_REFUND).
                eq(KingFinancePayBillEntity::getId, payBill.getId()));
        if (!update) {
            log.error("应付票据Id->{}，修改结算状态失败.", payBill.getId());
            throw new RuntimeException("下推应付票据结算单失败！");
        }
        return AjaxResult.success("应付票据退票成功");
    }

    /**
     * 批量删除金蝶-财务-应付票据
     *
     * @param ids 需要删除的金蝶-财务-应付票据ID
     * @return 结果
     */
    @Override
    public AjaxResult deleteKingFinancePayBillEntityByIds(String[] ids) {
        boolean update = this.update(new LambdaUpdateWrapper<KingFinancePayBillEntity>().
                set(KingFinancePayBillEntity::getIsUsed, ConstUtil.IS_USED_NO).
                in(KingFinancePayBillEntity::getId, ids));
        if (!update) {
            throw new CustomException("删除应付票据失败！");
        }
        return AjaxResult.success();
    }

    /**
     * 删除金蝶-财务-应付票据信息
     *
     * @param id 金蝶-财务-应付票据ID
     * @return 结果
     */
    @Override
    public int deleteKingFinancePayBillEntityById(String id) {
        return kingFinancePayBillEntityMapper.deleteKingFinancePayBillEntityById(id);
    }


    /**
     * 根据往来单位类型，获取往来单位和付款单位
     *
     * @param companyType：单位类型，根据往来单位或付款单位的类型魔法值
     * @param companyId：单位Id，根据单位类型，选择的具体单位Id
     * @return
     */
    private String getCompanyName(String companyType, String companyId) {
        if (StringUtils.isBlank(companyType) || StringUtils.isBlank(companyId)) {
            return "";
        }
        String transactionCompany = "";
        switch ( companyType ) {
            case "BD_Customer":
                CustomerEntity customerEntity = iCustomerService.getById ( companyId );
                if ( customerEntity != null )
                    transactionCompany = customerEntity.getCustomerName ();
                break;
            case "BD_Supplier":
                SupplierEntity supplierEntity = iSupplierService.getById ( companyId );
                if ( supplierEntity != null )
                    transactionCompany = supplierEntity.getSupplierName ();
                break;
            case "FIN_OTHERS":
                KingBaseTransactionsCompanyEntity transactionsCompanyEntity = iKingBaseTransactionsCompanyService.getById ( companyId );
                if ( transactionsCompanyEntity != null )
                    transactionCompany = transactionsCompanyEntity.getTitle ();
                break;
            case "ORG_Organizations":
                SysDept organ = iSysDeptService.getById ( companyId );
                if ( organ != null )
                    transactionCompany = organ.getDeptName ();
                break;
        }
        return transactionCompany;
    }

}
